package cn.com.dhcc.turbo.web.controller.registry;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.entity.registry.AdapterBase;
import cn.com.dhcc.turbo.entity.registry.DataCategory;
import cn.com.dhcc.turbo.entity.registry.OrgInfo;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncType;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.service.exch.ApiUserAuthService;
import cn.com.dhcc.turbo.service.registry.AdapterBaseService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.DataCategoryService;
import cn.com.dhcc.turbo.service.registry.OrgInfoService;
import cn.com.dhcc.turbo.service.registry.sync.ISynchronizeToGapService;

/**
 * 适配器 controller
 * 
 * @日期：2014-10-20  
 * @作者：古玉龙
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("/registry")
@TurboMenu(belongToMenu = LEAF_MENU.ADAPTER_MGR)
public class AdapterBaseController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.TURBO);
	@Autowired
	private AdapterBaseService adapterService;
	
	
	@Autowired
	private ISynchronizeToGapService synchronizeToGapService;
	
	@Autowired
	@Qualifier(AppIocBean.BASE_INFO_SERVICEIMPL_BEAN)
	BaseInfoService baseInfoService;
	@Autowired
	private DataCategoryService dataCategoryService;
	
	
	@Autowired
	ApiUserAuthService apiUserAuthService;
	@Autowired
	private OrgInfoService orgInfoService;
	
	/**
	 * 获取适配器基本信息
	 * 
	 * @param model
	 * @param pager
	 * @return
	 */
	@RequestMapping(value = "/adapter_base_list")
	public String list(HttpSession httpSession,Model model, Pager pager,String adapterCode,
			String adapterName,String dataCode,String adapterType){
		WhereCondition condition = new WhereCondition();
		try {
			String orgCode = NodeInfoParam.NODE_REGION_CODE;
			String pNodeCode =orgInfoService.getParentCode(orgCode);
			OrgInfo pOrgNode = orgInfoService.get(pNodeCode);
			condition.where().leftBracket().eq("t.adapter_type", "0");//全局适配器
			
			if (adapterType==null) {
				adapterType="0";
			}
			
			if(pOrgNode != null){
				condition.or().leftBracket().eq("t.adapter_type", "1").and().eq("t.org_code", pOrgNode.getAdCd()).rightBracket();//上级管理节点建立的适配器
			}
			condition.or().leftBracket().eq("t.adapter_type", "1").and().eq("t.org_code", orgCode).rightBracket().rightBracket();//本节点建立的适配器
			
			if (StrUtil.isNotBlank(adapterName)) {
				condition.and().like("t.ADAPTER_NAME", "%"+adapterName+"%");
			}
			
			if (StrUtil.isNotBlank(dataCode)) {
				condition.and().eq("t.data_code", dataCode);
			}
			
			if (StrUtil.isNotBlank(adapterType)) {
				condition.and().eq("t.adapter_type", adapterType);
			}
			
			condition.orderBy("t.mtime  desc");
			PagerData<AdapterBase> pagerData = adapterService.getAdapterBaseList(pager, condition,orgCode);
			model.addAttribute(DATA_KEY, pagerData.getDatas());
			setTotoal(model, pagerData.getTotal());
			
			//数据分类
			condition = new WhereCondition();
			//获取本节点的行政区号
			condition.where().eq("dc_type", "0");//全局适配器
			if(pOrgNode != null){
				condition.or().leftBracket().eq("dc_type", "1").and().eq("org_code", pOrgNode.getAdCd()).rightBracket();//上级管理节点建立的适配器
			}
			condition.or().leftBracket().eq("dc_type", "1").and().eq("org_code", orgCode).rightBracket();//本节点建立的适配器
			List<DataCategory>  dataCategory_list=dataCategoryService.list(condition);
			model.addAttribute("dataCategory_list", dataCategory_list);
			
			//节点管理权限
			UserInfo user = (UserInfo)getCurrentUserInfo(httpSession);
			if(user != null){
				model.addAttribute("nodeAdmin", user.getUserType());
			}
			
			model.addAttribute("netType", NodeInfoParam.isInnerNode());
		} catch (ServiceException e) {
			logger.error("获取适配器基础信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/adapter_base_list";
		
	}
	
	/**
	 * 获取系统服务基本信息
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/adapter_base_get", method = RequestMethod.GET)
	public String getAdapterBase(Model model, String id) {
		try {
			model.addAttribute(DATA_KEY, adapterService.get(id));
		} catch (Exception e) {
			logger.error("获取适配器基础信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/adapter_base_get";
	}
	
	/**
	 * 适配器添加
	 * @return
	 */
	@RequestMapping(value = "/adapter_base_add")
	public String adapterAdd(Model model) throws DaoException {
		try {
			String orgCode = NodeInfoParam.NODE_REGION_CODE;
			String pNodeCode =orgInfoService.getParentCode(orgCode);
			OrgInfo pOrgNode = orgInfoService.get(pNodeCode);
			//数据分类
			WhereCondition condition = new WhereCondition();
			//获取本节点的行政区号
			condition.where().eq("dc_type", "0");//全局适配器
			if(pOrgNode != null){
				condition.or().leftBracket().eq("dc_type", "1").and().eq("org_code", pOrgNode.getAdCd()).rightBracket();//上级管理节点建立的适配器
			}
			condition.or().leftBracket().eq("dc_type", "1").and().eq("org_code", orgCode).rightBracket();//本节点建立的适配器
			List<DataCategory> dataList = dataCategoryService.list(condition);
			model.addAttribute("dataList", dataList);
		} catch (Exception e) {
			logger.error("添加适配器信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/adapter_base_add";
	}

	/**
	 * 
	 * @param model
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/add_adapter_base", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addAdapter(Model model, AdapterBase vo) {
		try {
			String adapterType = vo.getAdapterType();
			String orgCode = NodeInfoParam.NODE_REGION_CODE;
			vo.setId(UUIDGenerator.getUUID());
			//12位
			DecimalFormat df = new DecimalFormat("000000000000");
			long maxCode=adapterService.localMaxCode(adapterType,orgCode);
			String adapterCode ="";
			if("1".equals(adapterType)){
				if("1".equals(maxCode)){
					df = new DecimalFormat("000000");
					adapterCode = orgCode+df.format(maxCode); 
				}else{
					adapterCode = orgCode+df.format(maxCode).substring(6); 
				}
			}else{
				adapterCode =df.format(maxCode); 
			}
			vo.setAdapterCode(adapterCode);
			vo.setOrgCode(orgCode);
			vo.setMtime(new Date());
			vo.setStatus("0");//可用
			//TODO BY 适配器基础信息注册同步
			adapterService.insertAdapterBaseAndSync(vo);
			return jsonSuccessResult("添加适配器信息成功");
		} catch (Exception e) {
			logger.error("添加适配器信息失败", e);
			return jsonFailResult("添加适配器信息失败");
		}
	}

	@RequestMapping(value = "/adapter_base_update/{id}", method = RequestMethod.GET)
	public String adapterUpdate(@PathVariable String id, Model model) {
		try {
			AdapterBase vo = adapterService.get(id);
			//数据分类
			String orgCode = NodeInfoParam.NODE_REGION_CODE;
			String pNodeCode =orgInfoService.getParentCode(orgCode);
			OrgInfo pOrgNode = orgInfoService.get(pNodeCode);
			//数据分类
			WhereCondition condition = new WhereCondition();
			//获取本节点的行政区号
			condition.where().eq("dc_type", "0");//全局适配器
			if(pOrgNode != null){
				condition.or().leftBracket().eq("dc_type", "1").and().eq("org_code", pOrgNode.getAdCd()).rightBracket();//上级管理节点建立的适配器
			}
			condition.or().leftBracket().eq("dc_type", "1").and().eq("org_code", orgCode).rightBracket();//本节点建立的适配器
			List<DataCategory> dataList = dataCategoryService.list(condition);
			model.addAttribute("dataList", dataList);
			model.addAttribute(DATA_KEY, vo);
		} catch (Exception e) {
			logger.error("添加适配器信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/adapter_base_update";
	}

	/**
	 * 修改适配器
	 * @param model
	 * @param vo
	 * @param newNodeName
	 * @return
	 */
	@RequestMapping(value = "/update_adapter_base", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateAdapter(AdapterBase vo, Model model) {

		try {
				vo.setMtime(new Date());
				//TODO BY 适配器基础信息更改同步
				adapterService.updateAdapterBaseAndSync(vo);
				return jsonSuccessResult("修改适配器成功");
		} catch (Exception e) {
			logger.error(" 修改适配器信息失败", e);
			return jsonFailResult("修改适配器信息失败");
		}
	}

	/**
	 * 根据Id禁用适配器
	 * 
	 * @param id
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/adapter_base_locked")
	@ResponseBody
	public Map<String, Object> lockedById(String id, Model model) {
		try {

			AdapterBase vo = adapterService.get(id);
			vo.setMtime(new Date());
			vo.setStatus("1");
			//TODO BY 适配器基础信息更改同步
			adapterService.update(vo);
			return jsonSuccessResult("适配器停止使用");
		} catch (Exception e) {
			return jsonFailResult("适配器禁用失败");
		}
	}

	/**
	 * 根据Id启用适配器
	 * 
	 * @param id
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/adapter_base_unlocked")
	@ResponseBody
	public Map<String, Object> unLockedById(String id, Model model) {
		try {
			AdapterBase vo = adapterService.get(id);
			vo.setMtime(new Date());
			vo.setStatus("0");
			//TODO BY 适配器基础信息更改同步
			adapterService.update(vo);
			return jsonSuccessResult("适配器启用成功");
		} catch (Exception e) {
			return jsonFailResult("适配器启用失败");
		}
	}
	
	
	/**
	 * 根据Id启用适配器
	 * 
	 * @param id
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/adapter_base_sync")
	@ResponseBody
	public Map<String, Object> sync() {
		try {
			List<AdapterBase> list=adapterService.list(new WhereCondition());
			synchronizeToGapService.sendToGap(list, SyncType.ADAPTER_BASE, 
					NodeInfoParam.GAP_PARAM.IP, NodeInfoParam.GAP_PARAM.Port, 
					NodeInfoParam.GAP_PARAM.Home, NodeInfoParam.GAP_PARAM.UserName,
					NodeInfoParam.GAP_PARAM.Password);
			return jsonSuccessResult("适配器同步到网闸成功");
		} catch (Exception e) {
			return jsonFailResult("适配器同步到网闸失败,请稍后再试"+e);
		}
	}
	
	
}
